package com.third.device.mg.serialport.help

import com.third.device.mg.serialport.listener.ConnectListener
import org.jetbrains.annotations.NotNull

/**
 * company 广东玛格家居有限公司
 * @author smoker
 * @Date 2021/12/29
 * Description:Socket管理者
 */
@Deprecated("启用,采用Netty框架" ,ReplaceWith("SocketBootstrapManager"),DeprecationLevel.WARNING)
internal class SocketManagers {
    //子Socket的集合
    private val unitMap by lazy { hashMapOf<String, SocketUnit>() }
    /*连接状态的监听*/
    private var connectListener : ConnectListener? = null

    /**
     * 根据ip 和 端口获取key
     */
    fun getUnitKey(ip: String, port: Int) = SocketUnit.createKey(ip, port)


    /**
     * 创建一个新Socket
     */
    fun createSocket(ip: String, port: Int): SocketUnit {
        val key = getUnitKey(ip, port)
        unitMap[key]?.let {
            /*如果已有Socket数据，但是已断开连接，那么重新连接*/
            if (it.refreshSocketState() != SocketUnitState.ConnectSuccess){
                it.connectSocket()
            }
            connectListener?.let { listener ->
                it.addConnectListener(listener)
            }
            return it
        } ?: let {
            val unit = SocketUnit(ip, port)
            connectListener?.let { listener ->
                unit.addConnectListener(listener)
            }
            unitMap[key] = unit
            return unit
        }
    }

    /**
     * 销毁一个Socket连接
     */
    fun destroySocket(ip: String, port: Int){
        val key = getUnitKey(ip, port)
        unitMap.remove(key)?.onDestroy()
    }

    /**
     * 预设置Socket连接的监听
     * 后续创建Socket的连接监听将会回调到[listener]
     */
    fun setConnectListener(listener: ConnectListener){
        this.connectListener = listener
    }

    /**
     * 添加连接的监听
     * 所有Socket的监听都会被替换
     */
    fun addConnectListener(listener: ConnectListener){
        this.connectListener = listener
        for ((_, unit) in unitMap) {
            unit.addConnectListener(listener)
        }
    }



    /**
     * 写入数据
     * @param ip   目标IP地址
     * @param port 目标端口
     * @param content 写入的内容
     */
    fun write(@NotNull ip:String, port:Int, content:ByteArray){
        if (content.isEmpty()){
            connectListener?.writeErrorListener(ip ,port ,"内容空" ,SocketErrorState.ContentNull)
        }else{
            val key = getUnitKey(ip ,port)
            unitMap[key]?.write(content) ?:let {
                connectListener?.writeErrorListener(ip ,port ,"无当前地址的Socket" ,SocketErrorState.SocketNull)
            }
        }
    }


    fun onDestroy() {
        closeAll()
    }

    private fun closeAll() {
        for ((_, unit) in unitMap) {
            unit.onDestroy()
        }
    }
}